//
//  StatusPictureView.swift
//  MyBlog
//
//  Created by lvtienan on 15/8/6.
//  Copyright © 2015年 ltn. All rights reserved.
//

import UIKit
import SDWebImage

// 可重用 cell 标识符
private let StatusPictureViewCellID = "StatusPictureViewCellID"

class StatusPictureView: UICollectionView {
    var statuses: Status? {
        didSet {
            
            // 更新视图
            reloadData()
            
            sizeToFit()

        }
    }
    
    override func sizeThatFits(size: CGSize) -> CGSize {
        return calcViewSize()
    }
    
    // 计算视图的大小
    private func calcViewSize() -> CGSize {
        
        // 准备常量
        let itemSize = CGSize(width: 90, height: 90)
        pictureLayout.itemSize = itemSize
        let itemMargin: CGFloat = 10
        // 每行最多显示的图片数量
        let rowCount = 3
        // 图片总数
        let count = statuses?.pictureURLs?.count ?? 0
        
        // 没有图片
        if count == 0 {
            return CGSizeZero
        }
        // 有一张图片
        if count == 1 {
            // 从SDWebImage 获取图片缓存大小
            let key = statuses!.pictureURLs![0].absoluteString
            // 提示 image 未必一定会缓存
            let image = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(key)

            // 判断图像是否存在, 设置临时大小
            var size = CGSizeMake(150, 120)
            if image != nil {
                size = image.size
            }
            // 对图像尺寸做进一步判断
            size.width = size.width < 40 ? 40 : size.width
            size.width = size.width > UIScreen.mainScreen().bounds.width ? 150 : size.width
            
            pictureLayout.itemSize = size
            return size
        }
        // 有4张图片
        if count == 4 {
            let w = itemSize.width * 2 + itemMargin
            return CGSize(width: w, height: w)
        }
        
        // 其它情况 2,3--5,6 --7,8,9
        // 计算有几行
        let row = (count - 1) / rowCount + 1
        let w = itemSize.width * CGFloat(rowCount) + itemMargin * CGFloat (rowCount - 1)
        let h = itemSize.height * CGFloat(row) + itemMargin * CGFloat(row - 1)
        return CGSize(width: w, height: h)
        
    }
    
    // collectionView初始化的时候必须设置UICollectionViewFlowLayout
    let pictureLayout = UICollectionViewFlowLayout()
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        super.init(frame: frame, collectionViewLayout: pictureLayout)
        
        backgroundColor = UIColor(white: 0.9, alpha: 1.0)
        
        // 注册可重用 cell
        registerClass(StatusPictureViewCell.self, forCellWithReuseIdentifier: StatusPictureViewCellID)
        
        // 设置数据源代理
        self.dataSource = self
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

extension StatusPictureView: UICollectionViewDataSource {
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return statuses?.pictureURLs?.count ?? 0
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(StatusPictureViewCellID, forIndexPath: indexPath) as! StatusPictureViewCell
       // cell.backgroundColor = UIColor.darkGrayColor()
        cell.imageURL = statuses!.pictureURLs![indexPath.item]
        return cell
    }
}

class StatusPictureViewCell: UICollectionViewCell {
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    var imageURL: NSURL? {
        didSet {
            iconView.sd_setImageWithURL(imageURL!)
        }
    }
    
    // 设置界面
    private func setupUI() {
        // 1.添加控件
        contentView.addSubview(iconView)
        
        // 2. 设置布局
        iconView.ff_Fill(contentView)
    }
    
    
    // MARK: - 懒加载控件
    private lazy var iconView:UIImageView = {
        let iv = UIImageView()
        iv.contentMode = UIViewContentMode.ScaleAspectFill
        iv.clipsToBounds = true
        return iv
    }()
}


